package com.ply.flashsalessystem.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ply.flashsalessystem.entity.vo.manage.JionRepositoryVo;
import com.ply.flashsalessystem.exception.GoodsException;
import com.ply.flashsalessystem.entity.pojo.JionRepository;
import com.ply.flashsalessystem.entity.pojo.JionRepositoryDetails;
import com.ply.flashsalessystem.entity.wrapper.JoinWrapper;
import com.ply.flashsalessystem.mapper.GoodsMapper;
import com.ply.flashsalessystem.mapper.JionRepositoryMapper;
import com.ply.flashsalessystem.service.JionRepositoryDetailsService;
import com.ply.flashsalessystem.service.JionRepositoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ply.flashsalessystem.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XiaoPan
 * @since 2022-03-23
 */
@Service
public class JionRepositoryServiceImpl extends ServiceImpl<JionRepositoryMapper, JionRepository> implements JionRepositoryService {
    @Autowired
    JionRepositoryMapper jionRepositoryMapper;

    @Autowired
    JionRepositoryDetailsService jionRepositoryDetailsService;

    @Autowired
    GoodsMapper goodsMapper;

    // 增加入库记录
    @Override
    @Transactional
    public boolean addRepository(List<JionRepositoryDetails> list){
        JionRepository jionRepository = new JionRepository();
        jionRepository.setManageId(UserUtils.getUserId());

        jionRepositoryMapper.insert(jionRepository);
        //获取 仓库id
        Integer jrId = jionRepository.getJrId();
        log.debug("jionRepository.getJrId():{}" + jionRepository.getJrId());

        // 每个 增加 入库 id
        for (JionRepositoryDetails jionRepositoryDetails : list) {
            //判断商品 id 的 是否存在
            if (goodsMapper.selectById(jionRepositoryDetails.getGoodsId()) == null) {
                throw new GoodsException("商品id不存在");
            }
            //判断 数量 和 成本 不为 空
            if (jionRepositoryDetails.getAllCost() <= 0 || jionRepositoryDetails.getNums() <= 0){
                throw new GoodsException("商品数量问题");
            }
            jionRepositoryDetails.setJrId(jrId);
        }
        log.debug("list:{}" + list);
        jionRepositoryDetailsService.saveBatch(list);
        return true;
    }


    // 条件 查询 入库记录
    @Override
    public Page<JionRepositoryVo> queryJoinRepository(Integer current, Integer limit, JoinWrapper joinWrapper) {
        return jionRepositoryMapper.queryJoinRepository(new Page<>(current, limit), joinWrapper);
    }
}
